#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#define SERVPORT 3333
#define MAXDATASIZE 100

int main(int argc,char *argv[]) {
    int sockfd, sendbytes;
    char buf[MAXDATASIZE];
    struct hostent* host;
    struct sockaddr_in serv_addr;
	char send_line[MAXDATASIZE];

    if(argc < 2) {
        fprintf(stderr, "Please enter the server's hostname");
        exit(1);
    }

    if((host = gethostbyname(argv[1])) == NULL) { //转换为hostent
        perror("gethostbyname");
        exit(1);
    }
	
	// 1. 创建 client socket （基于 TCP 传输）
    if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("创建 client socket 失败");
        exit(1);
    }
	
	// 2. 设置服务端连接地址 (IPv4 + PORT)
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERVPORT);
    serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
	
	// 3. 连接服务端 
    if((connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))) == -1) {
        perror("connect error");
        exit(1);
    }
	
	// 4. 给服务端发送数据
	for (;;) {
		if (fgets(send_line, MAXDATASIZE, stdin) != NULL) {
            if (!strcmp(send_line, "quit\n")) {
                break;
            }
			int i = strlen(send_line);
			// 用空字符代替换行符
            if (send_line[i - 1] == '\n') {
				// ascii 码为 0 表示的是空字符
                send_line[i - 1] = 0;
           	}
            printf("sending '%s'\n", send_line);
            size_t rt = write(sockfd, send_line, strlen(send_line));
            if (rt < 0) {
                perror("write failed");
            }
            printf("sended bytes: %zu \n", rt);
        }

	}
	
	// 5. 关闭 client socket
    close(sockfd);

}
